#include "graph.h"

/* Allocates memory and initalizes the graph */
matrixADT NewGraph(int size_x, int size_y) {
	int i;
	matrixADT graph = New(matrixADT);

	graph->size = size_x;
	graph->size_y = size_y;
	graph->nodes = (int**) malloc(sizeof(int) * size_x);

	for (i=0; i<size_x; i++)
		graph->nodes[i] = (int*) malloc(sizeof(int) * size_y);

	return graph;
}

/* Loads a graph from an external text file */
matrixADT loadGraph(string fileName) {
	FILE *inFile;
	matrixADT graph;
	int i, j, nVerticies;

	if ((inFile = fopen(fileName, "r")) != NULL) {
		nVerticies = StringToInteger(ReadLine(inFile));
		graph = NewGraph(nVerticies, nVerticies);
		for (i=0; i<nVerticies; i++) {
			for (j=0; j<nVerticies; j++) {
				fscanf(inFile, "%4d", &graph->nodes[i][j]);
			}
		}
		fclose(inFile);
	} else {
		printf("Couldn't open the selected graph.\n");
		graph = NULL;
	}
	return graph;
}

/* Prints a graph */
void printGraph(matrixADT graph) {
	int i, j, max;

	printf("\n");
	for (i=0; i<graph->size; i++)
		for (j=1; j<=graph->size_y; j++){
			max = getMax(graph->size, graph->size_y);
			printf("%3d %s", graph->nodes[i][j-1],
				(j % max == 0 ? "\n" : ""));
		}
	printf("\n");
}
static int getMax(int a, int b) {
	return (a > b ? a : b);
}